package com.gopay.checkorder.service.impl;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.gopay.checkorder.dao.BankAuthOrderDAO;
import com.gopay.checkorder.service.AdPayAuthOrderService;
import com.gopay.checkorder.service.BankAuthOrderService;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BisBankBusinessProd;
import com.gopay.common.constants.bank.BisBankInterfaceChannel;
import com.gopay.common.constants.bank.CmbcConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankAuthOrder;
import com.gopay.common.domain.bank.cmbc.expay.CmbcExPayMessage;
import com.gopay.common.domain.bank.cmbc.expay.samebank.CmbcAdPayMessage;
import com.gopay.common.domain.cps.vo.CPSRequest;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.bank.BisCertificationRemoteService;
import com.gopay.remote.cps.dispatch.CPSCallRemoteService;
import com.gopay.remote.cps.vo.Trans00664RemoteVo;

/**
 * 鉴权查询service
 * 
 * @AdPayAuthOrderServiceImpl.java
 * @author lilili
 * @2017-1-17 上午11:53:31 www.gopay.com.cn Inc.All rights reserved.
 */

@Service("adPayAuthOrderService")
public class AdPayAuthOrderServiceImpl implements AdPayAuthOrderService {

	private final static Logger logger = LoggerFactory.getLogger("CHECK-ORDER");

	@Resource(name = "bankAuthOrderDAO")
	private BankAuthOrderDAO bankAuthOrderDAO;

	@Resource(name = "bankAuthOrderService")
	private BankAuthOrderService bankAuthOrderService;

	@Resource(name = "bisCertificationClient")
	private BisCertificationRemoteService bisCertificationService;

	@Resource(name = "callCPS")
	private CPSCallRemoteService callCPS;

	@Override
	public void checkOrder(BankAuthOrder bankAuthOrder, String target) {
		try {
			logger.error("AdPayAuthOrderServiceImpl--bankAuthOrder--" + ToStringBuilder.reflectionToString(bankAuthOrder));
			if (bankAuthOrder == null) {
				logger.error("bankAuthOrder is null.");
			} else {
				// 更新对账次数
				bankAuthOrderDAO.updateTotalCheckTimes(bankAuthOrder);
				CmbcAdPayMessage message = new CmbcAdPayMessage();
				String merDate = bankAuthOrder.getOrderId().substring(0, 8);
				message.setOriOrderDate(merDate);
				message.setOrderId(bankAuthOrder.getOrderId()); // 国付宝系统订单号
				message.setBankOrderId(bankAuthOrder.getOutOrderId());
				message.setBank(bankAuthOrder.getBankCode());
				message.setBankIntrChann(BisBankInterfaceChannel.get(bankAuthOrder.getInterfaceChennelCode()));
				message.setBankBusProd(BisBankBusinessProd.get(bankAuthOrder.getBankBizProdCode()));
				message.setOrderDate(DateUtils.format(bankAuthOrder.getSendBankTm(), "yyyyMMddHHmmss"));
				Result result = bisCertificationService.queryCertification(message);
				if (result == null || !result.isSuccess()) {
					logger.error("AdPayAuthOrderServiceImpl checkOrder. 系统返回对账结果为空！");
					return;
				}
				CmbcExPayMessage resMsg = (CmbcExPayMessage) result.getDefaultModel();
				if (resMsg == null) {
					// 查询结果为空
					logger.error("fail:orderId:" + bankAuthOrder.getOrderId() + " errcode:" + ProcCodeConstants.PROC_CODE_100E6022 + " err:bis query is null.");
					return;
				}
				Trans00664RemoteVo vo00664 = new Trans00664RemoteVo();
				if (result.isSuccess()) {
					if (resMsg.isFlag()) {
						if (CmbcConstants.RESP_TYPE_SUCCESS.equals(resMsg.getRetType()) && CmbcConstants.EXEC_CODE_SUCCESS.equals(resMsg.getRetCode())
								&& CmbcConstants.RESP_TYPE_SUCCESS.equals(resMsg.getOriRetType()) && CmbcConstants.EXEC_CODE_SUCCESS.equals(resMsg.getOriRetCode())
								&& CmbcConstants.VALIDATE_STATUS_SUCCESS.equals(resMsg.getValidStatus())) {
                            logger.error("鉴权查询订单：" + bankAuthOrder.getOrderId() + "的交易成功" + "返回码：" + resMsg.getOriRetCode() + "返回信息：" + resMsg.getOriRetMsg() + "鉴权状态："
                                    + resMsg.getValidStatus());
							// 通知cps认证结果
							vo00664.setResultSuccess(true);
							vo00664.setGopayOrderId(bankAuthOrder.getOrderId());
							vo00664.setFlag(true);
							CPSResponse cpsres = callByVOTicket(vo00664);
							if (cpsres.getRespCode().equals(ProcCodeConstants.PROC_CODE_400DS014)) {
								// 更新认证主订单为认证通过
								bankAuthOrderService.updateAutoQuerySuccess(resMsg);
							}
							logger.error("AdPayAuthOrderServiceImpl checkOrder success notify cps res: " + ToStringBuilder.reflectionToString(cpsres));
						} else {
							logger.error("鉴权查询订单：" + bankAuthOrder.getOrderId() + "的交易未知，系统暂不处理" + "返回码：" + resMsg.getOriRetCode() + "返回信息：" + resMsg.getOriRetMsg());
						}
					} else {
						logger.error("AdPayAuthOrderServiceImpl checkOrder 返回处理结果：国付宝订单号【" + bankAuthOrder.getOrderId() + "】验签失败");
					}
				}
			}
		} catch (GopayException e) {
			logger.error(bankAuthOrder.getOutOrderId() + " AdPayAuthOrderServiceImpl checkOrder error", e);
		} catch (Exception e) {
			logger.error(bankAuthOrder.getOutOrderId() + " AdPayAuthOrderServiceImpl checkOrder error", e);
		}
	}

	private CPSResponse callByVOTicket(Object v) throws GopayException {
		CPSResponse response = null;
		try {
			// 封装调用cps服务的请求baggage
			Map<String, Object> baggage = new HashMap<String, Object>();
			baggage.put("s", "0");
			baggage.put("t", "001");
			baggage.put("v", v);

			// 封装cps请求对象
			CPSRequest request = new CPSRequest();
			request.setSequence(System.currentTimeMillis());
			request.setReqData(baggage);

			// 调用cps服务
			response = callCPS.callCPS(request);

			// 校验调用序列值是否相同
			if (response.getSequence() != request.getSequence()) {
				throw new GopayException(ProcCodeConstants.PROC_CODE_100F3001);
			}

		} catch (Exception e) {
			logger.error("通知cps异常！！！", e);
			throw new GopayException(ProcCodeConstants.PROC_CODE_100F3001);
		}
		return response;
	}

}
